package com.huasheng.infohub.actions;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.huasheng.infohub.dao.EmailDao;
import com.huasheng.infohub.dao.impl.EmailDaoMysql;
import com.huasheng.infohub.utils.Consts;
import com.huasheng.infohub.utils.FailedEmail;

public class ImportEmailsAction extends BaseAction {
	private static final long serialVersionUID = -1438580771978584830L;
	static private Logger log = Logger.getLogger(ImportEmailsAction.class);
	
	private String emails;
	
	private boolean status;
	private List<String> imported;
	private List<FailedEmail> failed;
	private String reason;
	
	private EmailDao emailDao =  new EmailDaoMysql();

	public String add() {
		status = false;
		if (emails == null) {
			reason = "empty email";
			return SUCCESS;
		}
		
		String[] emailArray = emails.split(Consts.EmailSeperator);
		if(emailArray == null) {
			reason = "no emails after split";
			return SUCCESS;
		}

		if(!emailDao.init()) {
			reason = "fail to init emai dao";
			return SUCCESS;
		}
		
		imported = new ArrayList<String>();
		
		for(String email: emailArray) {
			if(email==null || email.isEmpty()) continue;
			uploadEmail(email);
		}
		
		emailDao.end();
		
		status = true;
		
		return SUCCESS;
	}

	private void uploadEmail(String email) {
		if(Pattern.matches(Consts.EmailPattern, email)) {
			try {
				emailDao.insert(email, 1, 1);
				imported.add(email);
			} catch (Throwable e) {
				FailedEmail failedEmail = new FailedEmail();
				failedEmail.setEmail(email);
				failedEmail.setReason(e.getMessage());
				
				if(failed==null) failed = new ArrayList<FailedEmail>();
				
				failed.add(failedEmail);
				
				if(log.isDebugEnabled()) {
					//e.p
					//log.
				}
			}
		} else {
			FailedEmail failedEmail = new FailedEmail();
			failedEmail.setReason("invalid email format");
			failedEmail.setEmail(email);
			
			if(failed==null) failed = new ArrayList<FailedEmail>();
			failed.add(failedEmail);
		}
	}
	
	public String getEmails() {
		return emails;
	}

	public void setEmails(String emails) {
		this.emails = emails;
	}

	public List<String> getImportedEmails() {
		return imported;
	}

	public void setImportedEmails(List<String> importedEmails) {
		this.imported = importedEmails;
	}

	public List<FailedEmail> getFailedEmails() {
		return failed;
	}

	public void setFailedEmails(List<FailedEmail> failedEmails) {
		this.failed = failedEmails;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public String getReason() {
		return reason;
	}

	public void setReason(String reason) {
		this.reason = reason;
	}
}
